package com.yqg.protection.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yqg.protection.common.Result;
import com.yqg.protection.common.interceptor.SysLog;
import com.yqg.protection.controller.dto.MapDataDto;
import com.yqg.protection.entity.Announce;
import com.yqg.protection.entity.EquipmentInputStore;
import com.yqg.protection.mapper.EquipmentInputStoreMapper;
import com.yqg.protection.service.IAnnounceService;
import com.yqg.protection.service.IEquipmentInputStoreService;
import com.yqg.protection.service.IEquipmentService;
import com.yqg.protection.service.ISimInputStoreService;
import com.yqg.protection.utils.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * EquipmentInputStoreController 前端控制器
 *
 * @author zxf
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/equipment-input-store")
@Api(tags = "设备入库管理")
public class EquipmentInputStoreController {

    @Resource
    private IEquipmentInputStoreService equipmentInputStoreService;

    @Autowired
    private EquipmentInputStoreMapper equipmentInputStoreMapper;

    @Autowired
    private IEquipmentService equipmentService;

    @Autowired
    private ISimInputStoreService simInputStoreService;

    @Autowired
    private IAnnounceService announceService;

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
    @ApiOperation("新增或更新设备入库信息")
    @SysLog("新增或者修改设备信息")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody EquipmentInputStore equipmentInputStore) {
        LambdaQueryWrapper<EquipmentInputStore> equipmentInputStoreQueryWrapper = new LambdaQueryWrapper<>();
        equipmentInputStoreQueryWrapper.eq(EquipmentInputStore::getEquipmentId, equipmentInputStore.getEquipmentId());
        equipmentInputStoreQueryWrapper.eq(EquipmentInputStore::getIsDelete, 0);
        EquipmentInputStore equipmentInputStore1 = equipmentInputStoreService.getOne(equipmentInputStoreQueryWrapper);
        if (ObjectUtil.isEmpty(equipmentInputStore.getId())) {
            if (equipmentInputStore1 != null) {
                return Result.error(Constants.CODE_500, "该设备已存在");
            }
            equipmentInputStore.setIsDelete(0);
            equipmentInputStore.setState("0");
        } else {
            if (equipmentInputStore1 != null && !equipmentInputStore.getId().equals(equipmentInputStore1.getId())) {
                return Result.error(Constants.CODE_500, "该设备已存在");
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String updateTime = simpleDateFormat.format(new Date());
            equipmentInputStore.setUpdateTime(updateTime);
        }
        equipmentInputStoreService.saveOrUpdate(equipmentInputStore);
        if (equipmentInputStore.getEndTime() != null && LocalDateTime.now().plusMonths(1L).isAfter(equipmentInputStore.getEndTime())) {
            LambdaQueryWrapper<Announce> announceQueryWrapper = new LambdaQueryWrapper<>();
            announceQueryWrapper.eq(Announce::getType, "0");
            announceQueryWrapper.eq(Announce::getEquipOrSimId, equipmentInputStore.getId());
            announceService.remove(announceQueryWrapper);
        }
        return Result.success();
    }

    /**
     * 删除
     */
    @GetMapping("delete/{id}")
    @ApiOperation("删除设备入库信息")
    @SysLog("删除设备信息")
    public Result delete(@PathVariable Integer id) {
        EquipmentInputStore equipmentInputStore = equipmentInputStoreService.getById(id);
        if (!equipmentInputStore.getState().equals("0")) {
            return Result.error(Constants.CODE_500, "设备已激活，无法删除");
        }
        equipmentInputStore.setIsDelete(1);
        return Result.success(equipmentInputStoreService.saveOrUpdate(equipmentInputStore));
    }

    /**
     * 查询所有
     */
    @GetMapping("/findNoBindingSIM")
    @ApiOperation("查询所有未绑定SIM卡的设备")
    public Result findNoBindingSIM(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize,
                                   String equipmentId,
                                   Integer level,
                                   Long organizationId,
                                   String isAllClient,
                                   @RequestParam List<Long> clientIds) {
        pageNum = pageNum * pageSize - pageSize;
        List<EquipmentInputStore> equipmentInputStores = equipmentInputStoreMapper.findNoBindingSIMPage(pageNum, pageSize, equipmentId, level, organizationId, isAllClient, clientIds);
        Long count = equipmentInputStoreMapper.findNoBindingSIMPageCount(equipmentId, level, organizationId, isAllClient, clientIds);
        HashMap<String, Object> map = new HashMap<>();
        map.put("record", equipmentInputStores);
        map.put("total", count);
        return Result.success(map);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询设备入库信息")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(equipmentInputStoreService.getById(id));
    }

    @GetMapping("/page")
    @ApiOperation("分页查询设备入库信息")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           String equipmentName,
                           String equipmentId,
                           Integer level,
                           Long organizationId,
                           String state,
                           Integer systemId,
                           Integer type,
                           String SIMId,
                           String clientName,
                           String isAllClient,
                           @RequestParam List<Long> clientIds,
                           Long id) {
        pageNum = pageNum * pageSize - pageSize;
        List<EquipmentInputStore> equipmentInputStores = equipmentInputStoreMapper.findPage(pageNum, pageSize, equipmentName, equipmentId, level, organizationId, state, systemId, type, SIMId, clientName, isAllClient, clientIds, id);
        Long count = equipmentInputStoreMapper.findPageCount(equipmentName, equipmentId, level, organizationId, state, systemId, type, SIMId, clientName, isAllClient, clientIds);
        HashMap<String, Object> map = new HashMap<>();
        map.put("record", equipmentInputStores);
        map.put("total", count);
        return Result.success(map);
    }

    @PostMapping("/updateState")
    @ApiOperation("更新设备状态")
    @SysLog("更新设备状态")
    @Transactional(rollbackFor = Exception.class)
    public Result updateState(@RequestBody EquipmentInputStore equipmentInputStore) {
//        if (equipmentInputStore.getSimInputStoreId() != null) {
//            equipmentInputStore.setDeviceBindingSim(1);
//        } else {
//            equipmentInputStore.setDeviceBindingSim(0);
//        }
//        if (equipmentInputStore.getState().equals("1")) {
//            SimInputStore simInputStore = simInputStoreService.getById(equipmentInputStore.getSimInputStoreId());
//            simInputStore.setDeviceBindingEquipment(1);
//            simInputStore.setDeviceBindingType(0);
//            simInputStore.setEquipmentInputStoreId(equipmentInputStore.getId());
//            simInputStoreService.updateById(simInputStore);
//        } else if (equipmentInputStore.getState().equals("0")) {
//            EquipmentInputStore equipmentInputStore1 = equipmentInputStoreService.getById(equipmentInputStore.getId());
//            SimInputStore simInputStore = simInputStoreService.getById(equipmentInputStore1.getSimInputStoreId());
//            simInputStore.setDeviceBindingEquipment(0);
//            simInputStore.setDeviceBindingType(null);
//            simInputStore.setEquipmentInputStoreId(null);
//            simInputStoreService.updateById(simInputStore);
//        }
        return Result.success(equipmentInputStoreService.saveOrUpdate(equipmentInputStore));
    }

    /**
     * 查询所有
     */
    @GetMapping("/findAllUrlName")
    public Result findAllUrlName() {
        List<EquipmentInputStore> list = equipmentInputStoreMapper.findAllUrlName();
        return Result.success(list);
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    @ApiOperation("查询所有设备")
    public Result all(Long organizationId, Integer level,String isAllClient,Integer systemId,
                      @RequestParam List<Long> clientIds,
                      Long clientId) {
        return Result.success(equipmentInputStoreMapper.selectlist(level, organizationId, isAllClient, systemId, clientIds, clientId));
    }

    @GetMapping("/homeAll")
    @ApiOperation("查询所有设备")
    public Result homeAll(Long organizationId, Integer level,String isAllClient,Integer systemId,
                      @RequestParam List<Long> clientIds,
                      Long clientId) {
        List<EquipmentInputStore> list = equipmentInputStoreMapper.selectlist(level, organizationId, isAllClient, systemId, clientIds, clientId);
        if (list.size() > 50) {
            list = list.subList(0, 50);
        }
        return Result.success(list);
    }

    @GetMapping("/findTypeCount")
    @ApiOperation("查询设备数量")
    public Result findTypeCount(Long organizationId, Integer level,String isAllClient,
                                @RequestParam List<Long> clientIds,
                                Long clientId) {
        return Result.success(equipmentInputStoreMapper.findTypeCount(level, organizationId, isAllClient, clientIds, clientId));
    }

    /**
     * 根据单位分组查询
     */
    @GetMapping("/findCountByClient")
    @ApiOperation("根据单位分组查询")
    public Result findCountByClient(Integer level,
                               Long organizationId,
                               String isAllClient,
                               @RequestParam List<Long> clientIds) {
        List<Map<String, Integer>> list = equipmentInputStoreMapper.findCountByClient(organizationId, level, isAllClient, clientIds);
        return Result.success(list);
    }

    /**
     * 根据单位分组查询
     */
    @GetMapping("/findCountByClientAndOnline")
    @ApiOperation("根据单位和在线状态分组查询")
    public Result findCountByClientAndOnline(Integer level,
                                    Long organizationId,
                                    String isAllClient,
                                    @RequestParam List<Long> clientIds) {
        List<Map<String, Integer>> list = equipmentInputStoreMapper.findCountByClientAndOnline(organizationId, level, isAllClient, clientIds);
        return Result.success(list);
    }

    /**
     * 根据单位分组查询
     */
    @GetMapping("/findMapByClient")
    @ApiOperation("根据单位分组查询地图数据")
    public Result findMapByClient(Integer level,
                                    Long organizationId,
                                    String isAllClient,
                                    @RequestParam List<Long> clientIds) {
        List<MapDataDto> list = equipmentInputStoreMapper.findMapByClient(organizationId, level, isAllClient, clientIds);
        return Result.success(list);
    }

    @ApiOperation("导出数据")
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       String equipmentName,
                       String equipmentId,
                       Integer level,
                       Long organizationId,
                       String state,
                       Integer systemId,
                       Integer type,
                       String SIMId,
                       String clientName,
                       String isAllClient,
                       @RequestParam List<Long> clientIds) {
        equipmentInputStoreService.export(response, equipmentName, equipmentId, level, organizationId, state, systemId, type, SIMId, clientName, isAllClient, clientIds);
    }

    @ApiOperation("导入数据")
    @PostMapping("/importData")
    @SysLog("导入设备信息")
    public void importData(MultipartFile file) {
        equipmentInputStoreService.importData(file);
    }

    /**
     * 根据单位分组查询
     */
    @GetMapping("/findCountByOnline")
    @ApiOperation("根据在线状态分组查询")
    public Result findCountByOnline(Integer level,
                                    Long organizationId,
                                    String isAllClient,
                                    @RequestParam List<Long> clientIds) {
        List<Map<String, Object>> list = equipmentInputStoreMapper.findCountByOnline(organizationId, level, isAllClient, clientIds);
        HashMap<Object, Object> map = new HashMap<>();
        Long allTotal = 0L;
        Long onlineTotal = 0L;
        Long unlineTotal = 0L;
        for (Map<String, Object> map1 : list) {
            if (map1.get("online").equals("online")) {
                onlineTotal = onlineTotal + (Long) map1.get("count");
            } else {
                unlineTotal = unlineTotal + (Long) map1.get("count");
            }
            allTotal = allTotal + (Long) map1.get("count");
        }
        map.put("allTotal", allTotal);
        map.put("onlineTotal", onlineTotal);
        map.put("unlineTotal", unlineTotal);
        return Result.success(map);
    }

    @GetMapping("/pageApp")
    @ApiOperation("APP分页查询设备入库信息")
    public Result pageApp(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           String equipmentName,
                           Integer level,
                           Long organizationId,
                           Integer type,
                           String online,
                           String isAllClient,
                           @RequestParam List<Long> clientIds) {
        pageNum = pageNum * pageSize - pageSize;
        List<EquipmentInputStore> equipmentInputStores = equipmentInputStoreMapper.findPageApp(pageNum, pageSize, equipmentName, level, organizationId, type, online, isAllClient, clientIds);
        Long count = equipmentInputStoreMapper.findPageAppCount(equipmentName, level, organizationId, type, online, isAllClient, clientIds);
        HashMap<String, Object> map = new HashMap<>();
        map.put("record", equipmentInputStores);
        map.put("total", count);
        return Result.success(map);
    }

    @GetMapping("/pageExpire")
    @ApiOperation("分页查询过期设备信息")
    public Result pageExpire(@RequestParam Integer pageNum,
                          @RequestParam Integer pageSize,
                          String equipmentName,
                          Integer level,
                          Long organizationId,
                          Integer isExpire,
                          String isAllClient,
                          @RequestParam List<Long> clientIds) {
        pageNum = pageNum * pageSize - pageSize;
        List<EquipmentInputStore> equipmentInputStores = equipmentInputStoreMapper.findPageExpire(pageNum, pageSize, equipmentName, level, organizationId, isExpire, isAllClient, clientIds);
        Long count = equipmentInputStoreMapper.findPageExpireCount(equipmentName, level, organizationId, isExpire, isAllClient, clientIds);
        HashMap<String, Object> map = new HashMap<>();
        map.put("record", equipmentInputStores);
        map.put("total", count);
        return Result.success(map);
    }
}

